<?php
/**
 * @orm tablename newsletters
 */
class Newsletter extends DomArObject {
	
	/**
	 * @orm char(50)
	 */
	public $name;
	/**
	 * @orm plugin DomArDateTime(now)
	 */
	public $createdTime;
	/**
	 * @orm char(50)
	 */
	public $template;
	
	/**
	 * @orm char(255)
	 */
	public $subject;
	/**
	 * @orm char(255)
	 */
	public $fromName;
	/**
	 * @orm char(255)
	 */
	public $fromEmail;
	/**
	 * @orm owns many NewsletterBlock inverse newsletter
	 */
	public $blocks;
	/**
	 * @orm has parent  NewsletterSend inverse newsletter
	 */
	public $sends;
	
	const ADMIN_TEMPLATES_DIR = 'Newsletters/'; // in media folder.
	
	const TEMPLATES_DIR = 'Newsletters/Templates/'; // in media folder.
	
	
	public static function getTemplates() {
		$list = array();
		$dir = DOM_TEMPLATES_DIR.self::TEMPLATES_DIR;
		foreach( glob($dir.'*') as $template ) {
			$info = $template.'/info.php';
			if( file_exists($info) ) {
				require( $info);
			} else {
				$INFO = array(
					'title' => str_replace( $dir, '', $template ),
					'description' => '',
				);
			}
			$INFO['dir'] = str_replace( $dir, '', $template );
			$list[] = $INFO;
		}
		return $list;
	}
	
	public static function getTemlatesList() {
		$list = array();
		foreach( self::getTemplates() as $template ) {
			$list[$template['dir']] = $template['title'];
		}
		return $list;
	}
	
	public static function getTemplateInfo( $template ) {
		$file = DOM_TEMPLATES_DIR.self::TEMPLATES_DIR.$template.'/info.php';
		require( $file );
		return $INFO;
	}
	
	public function renderForEmail() {
		return $this->render('email');
	}
	
	public function renderForWeb() {
		return $this->render('web');	
	}
	
	
	public function getPreparedMail() {
		$mail = new Mail();
		$mail->IsHTML(true);
		$mail->CharSet = 'utf-8';
		$mail->From = $this->fromEmail;
		$mail->FromName = $this->fromName;
		$mail->Subject = $this->subject;
		$mail->Body = $this->renderForEmail();
		return $mail;
	}
	
	private function render( $type ) {
		$view = new DomView( '/'.self::TEMPLATES_DIR.$this->template.'/template.html');
		$view->newsletter = $this;
		$view->renderType = $type;
		$view->blocks = $this->blocks->query()->orderBy('t.order')->commit()->toArray();
		return $view->fetch();
	}
	
	
}
?>